import { provide, ref } from "vue";
import { TableField } from "@/models/TableSetting";

export function SubTableSubmitForm(
  props: {
    tableData: Array<Record<string, unknown>>;
    tableFieldList: Array<TableField>;
    submitForm: Record<string, unknown>;
    submitFormDialog: {
      title: string;
      width: string;
    };
  },
  emit: {
    (
      e: "sub-table-delete",
      subTableDeleteResultTableData: Array<Record<string, unknown>>
    ): void;
    (
      e: "set-sub-table-form-init-value",
      type: string,
      row: Record<string, unknown>
    ): void;
    (
      e: "change-sub-table-record",
      subTableSubmitFunctionType: string,
      selectedIndex: number
    ): void;
  }
) {
  /**
   * 子表的新增或编辑窗口是否可见属性(false 不可见, true 可见).
   */
  const subTableSubmitFormDialogVisible = ref(false);
  provide("subTableSubmitFormDialogVisible", subTableSubmitFormDialogVisible);

  /**
   * 改变子表的新增或编辑窗口的状态(可见: true/不可见: false).
   */
  const changeSubTableSubmitFormDialogVisible = () => {
    subTableSubmitFormDialogVisible.value =
      !subTableSubmitFormDialogVisible.value;
  };
  provide(
    "changeSubTableSubmitFormDialogVisible",
    changeSubTableSubmitFormDialogVisible
  );

  /**
   *   子表弹窗的表单类型.(新增还是编辑)
   */
  const subTableSubmitFunctionType = ref();
  provide("subTableSubmitFunctionType", subTableSubmitFunctionType);

  /**
   * 设置子表弹窗的表单功能类型的值
   * @param type 表单类型.
   */
  const setSubTableSubmitFunctionType = (type: string) => {
    subTableSubmitFunctionType.value = type;
  };

  /**
   * 设置子表弹窗表单的初始值.
   * @param row 传入的当前行信息.
   */
  const setSubTableFormInitValue = (row: Record<string, unknown>) => {
    emit(
      "set-sub-table-form-init-value",
      subTableSubmitFunctionType.value,
      Object.assign({}, row)
    );
  };
  provide("setSubTableFormInitValue", setSubTableFormInitValue);

  const subTableFOrmIndex = ref(-1);

  const setSubTableFOrmIndex = (index: number) => {
    subTableFOrmIndex.value = index;
  };

  /**
   * 提交子表信息
   */
  const subTableFormSubmit = () => {
    const type = subTableSubmitFunctionType.value;
    emit("change-sub-table-record", type, subTableFOrmIndex.value);
  };
  provide("subTableFormSubmit", subTableFormSubmit);

  return {
    changeSubTableSubmitFormDialogVisible,
    setSubTableSubmitFunctionType,
    setSubTableFormInitValue,
    setSubTableFOrmIndex,
  };
}
